<template>
  <div class="index column">
    <PageHeader isBack :content="pageTitle"></PageHeader>
    <div class="container">
      <el-tree
        :data="roleData"
        node-key="userId"
        default-expand-all
        :expand-on-click-node="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span style="margin-right: 20px"
            ><el-tag v-if="node.level == 3" type="info">{{
              data.userName
            }}</el-tag
            ><span v-else>{{ data.userName }}</span></span
          >
          <span class="node-btns">
            <el-button
              size="mini"
              type="text"
              v-if="node.level == 2"
              @click="append(node, data)"
            >
              新增
            </el-button>
            <el-button
              v-if="node.level == 3"
              size="mini"
              type="text"
              @click="edit(node, data)"
            >
              编辑
            </el-button>
            <el-button
              v-if="node.level == 3"
              size="mini"
              type="text"
              @click="remove(node, data)"
            >
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <!-- 角色管理 -->
    <el-dialog
      :title="
        '添加' +
        (ruleForm.role == 1
          ? '超级管理员'
          : ruleForm.role == 2
          ? '校级管理员'
          : ruleForm.role == 3
          ? '院级管理员'
          : '学生')
      "
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="left"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input v-model="ruleForm.pass"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model.number="ruleForm.tel"></el-input>
        </el-form-item>
        <el-form-item label="所属学校" prop="schoolId">
          <el-select v-model="ruleForm.schoolId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.userId != null"
          label="选择角色"
          prop="role"
        >
          <el-select v-model="ruleForm.role" placeholder="请选择">
            <el-option
              v-for="item in roleOpts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">重 置</el-button>
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提 交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/user";
import PageHeader from "@/components/user/PageHeader";
export default {
  name: "role",
  components: {
    PageHeader,
  },
  data() {
    return {
      pageTitle: "用户编辑",
      isBack: true,
      dialogVisible: false,
      roleData: [
        {
          userId: 0,
          userName: "所有用户",
          children: [
            {
              userId: 1,
              userName: "超级管理员",
              children: [],
            },
            {
              userId: 2,
              userName: "校级管理员",
              children: [],
            },
            {
              userId: 3,
              userName: "院级管理员",
              children: [],
            },
            {
              userId: 4,
              userName: "学生",
              children: [],
            },
          ],
        },
      ],
      // 编辑表格内容
      // 学校选择
      roleOpts: [
        {
          value: 1,
          label: "超级管理员",
        },
        {
          value: 2,
          label: "校级管理员",
        },
        {
          value: 3,
          label: "院级管理员",
        },
        {
          value: 4,
          label: "学生",
        },
      ],
      options: [],
      ruleForm: {
        userId: null,
        role: "",
        name: "",
        pass: "",
        tel: "",
        schoolId: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
        pass: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
        tel: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { pattern: /^1[34578]\d{9}$/, message: "请输入正确的电话号码" },
        ],
        schoolId: [
          { required: true, message: "请选择学校", trigger: "change" },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
    };
  },

  mounted() {
    this.getAllSchool();
    this.getAllUser();
  },
  methods: {
    resetRoleData() {
      for (var i = 0; i < this.roleData[0].children.length; i++) {
        this.roleData[0].children[i].children = [];
      }
    },
    getAllSchool() {
      userApi.getAllSchool().then((res) => {
        var data = res.data.data;
        this.options = data.map((school) => {
          return { value: school.schoolId, label: school.schoolName };
        });
      });
    },
    getAllUser() {
      this.resetRoleData();
      userApi.getAllUser().then((res) => {
        var data = res.data.data;
        data.map((user) => {
          var index = parseInt(user.role) - 1;
          this.roleData[0].children[index].children.push(user);
        });
      });
    },
    //树节点的扩张
    append(node, data) {
      var level = node.level;
      this.dialogVisible = true;
      this.resetForm("ruleForm");
      console.log("append",data)
      this.ruleForm.role = data.userId;
    },
    edit(node, data) {
      this.dialogVisible = true;
      console.log("edit", data);
      this.ruleForm.userId = data.userId;
      this.ruleForm.role = data.role;
      this.ruleForm.name = data.userName;
      this.ruleForm.pass = data.password;
      this.ruleForm.tel = data.tel;
      this.ruleForm.schoolId = data.schoolId;
    },
    remove(node, data) {
      this.$confirm("此操作将永久删除该节点, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (node.childNodes.length > 0) {
            this.$message({
              message: "该节点下仍存在子节点,不可进行删除操作!",
              type: "warning",
            });
          } else {
            var formData = new FormData();
            formData.append("userId", data.userId);
            userApi.deleteUser(formData).then((res) => {
              var data = res.data.data;
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.resetRoleData();
              data.map((user) => {
                var index = parseInt(user.role) - 1;
                this.roleData[0].children[index].children.push(user);
              });
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 显示对话框
    closeDialog() {
      this.dialogVisible = false;
      this.resetForm("ruleForm");
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.closeDialog();
          done();
        })
        .catch((_) => {});
    },
    //角色添加/编辑
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var formData = new FormData();
          formData.append("userName", this.ruleForm.name);
          formData.append("role", this.ruleForm.role);
          formData.append("password", this.ruleForm.pass);
          formData.append("tel", this.ruleForm.tel);
          formData.append("schoolId", this.ruleForm.schoolId);
          console.log("当前表单:", this.ruleForm);
          if (this.ruleForm.userId == null) {
            userApi.registerUser(formData).then((res) => {
              var data = res.data;
              this.closeDialog();
              this.getAllUser();
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            });
          } else {
            formData.append("userId", this.ruleForm.userId);
            userApi.updateUser(formData).then((res) => {
              this.closeDialog();
              this.getAllUser();
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            });
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      if(this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.ruleForm = {
        userId: null,
        role: "",
        name: "",
        pass: "",
        tel: "",
        schoolId: "",
      };
    },
  },
};
</script>

<style scoped>
.index {
  width: 1000px;
  box-sizing: border-box;
  padding: 35px 0 0 0;
}
.container {
  margin-top: 35px;
}
/* 树形结构 */
::v-deep .el-tree-node__content {
  height: 40px;
}
</style>